package com.gobo.ucenterservice.controller;

import com.gobo.commonutils.JwtUtils;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import com.gobo.ucenterservice.pojo.UcenterMember;
import com.gobo.ucenterservice.service.UcenterMemberService;
import com.gobo.ucenterservice.utils.ConstantPropertiesUtil;
import com.gobo.ucenterservice.utils.HttpClientUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/ucenterservice/member/api/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @GetMapping("login")
    public String getWxCode(){

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 回调地址
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            throw new GoboException(20001, e.getMessage());
        }
        String qrcodeUrl = String.format(baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "Gobo");
        return "redirect:" + qrcodeUrl;

    }

    /**
     * 回调地址获取到code 以及state
     * @param code
     * @param state
     * @return
     */
    @GetMapping("callback")
    public String callback(String code, String state) {

        //得到授权临时票据code
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String codeUrl = String.format(baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            result = HttpClientUtils.get(codeUrl);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GoboException(20001,"WxLogin异常！");
        }
        //解析result为Map
        Gson gson = new Gson();
        HashMap map = gson.fromJson(result, HashMap.class);
        String accessToken = (String)map.get("access_token");
        String openid = (String)map.get("openid");
        UcenterMember member = memberService.getWxMemberInfo(openid);
        if (member==null){
            member = saveWxMemberInfo(openid,accessToken);
        }

        //登录 返回URL 带token
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return "redirect:http://localhost:3000?token="+token;

    }
    private UcenterMember saveWxMemberInfo(String openid,String accessToken){
        //获取用户个人信息
        String baseUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=%s" +
                "&openid=%s";
        String formatUrl = String.format(baseUrl,
                accessToken,
                openid);
        String result = null;
        try {
            result = HttpClientUtils.get(formatUrl);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GoboException(20001,"WxLogin异常！");
        }
        Gson gson = new Gson();
        //解析result为Map
        HashMap<String,Object> infoMap = gson.fromJson(result, HashMap.class);
        String nickname = (String)infoMap.get("nickname");
        String headimgurl = (String)infoMap.get("headimgurl");
        UcenterMember member = new UcenterMember();
        member.setNickname(nickname);
        member.setOpenid(openid);
        member.setAvatar(headimgurl);
        member.setSex((Integer) infoMap.get("sex"));
        memberService.save(member);
        return  member;
    }

}
